<template>
  <div :key="componentKey">
    <!--面包屑模块-->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="padding: 10px">
      <el-breadcrumb-item :to="{ path: '/manage/' + (id || '') }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>教学活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>我的发布</el-breadcrumb-item>
    </el-breadcrumb>
    
    <!--卡片视图区域-->
    <el-card>
      <div class="publish-container" :key="componentKey">
        <div class="publish-header">
          <h3>我的发布</h3>
          <div class="header-actions">
            <span v-if="selectedTests.length > 0" class="selected-count">
              已选择 {{ selectedTests.length }} 个测试
            </span>
            <el-button 
              type="success" 
              icon="el-icon-plus" 
              @click="goToTestPublish">
              新增
            </el-button>

            <el-button 
              v-if="!isDeleteMode"
              type="danger" 
              icon="el-icon-delete" 
              @click="enterDeleteMode">
              删除选中测试
            </el-button>
            <el-button 
              v-if="isDeleteMode"
              type="success" 
              icon="el-icon-check" 
              @click="confirmDelete"
              :disabled="selectedTests.length === 0">
              确认删除 ({{ selectedTests.length }})
            </el-button>
            <el-button 
              v-if="isDeleteMode"
              type="info" 
              icon="el-icon-close" 
              @click="cancelDeleteMode">
              取消
            </el-button>
            

          </div>
        </div>
        
        <el-tabs v-model="activeTab" type="card">
          <!-- 未截止测试标签页 -->
          <el-tab-pane label="未截止测试" name="pending">
            <div class="test-list">
              <!-- 空状态 -->
              <div v-if="pendingTests.length === 0" class="empty-state">
                <div class="empty-container">
                  <el-empty description="暂无未截止的测试">
                    <el-button type="primary" @click="goToTestPublish()">去发布试题</el-button>
                  </el-empty>
                </div>
              </div>
              <!-- 有内容状态 -->
              <div v-if="pendingTests.length !== 0" class="hierarchical-selection">
                <el-collapse accordion>
                  <el-collapse-item v-for="classData in classmap.values()" :key="classData.id">
                    <template slot="title">
                      <div class="class-header">
                        <span class="class-name">{{ classData.name }}</span>
                        <span class="class-count">{{ getClassTestCount(classData.id, 'pending') }} 个测试</span>
                      </div>
                    </template>
                    <!-- 该班级没有未截止测试时显示 -->
                    <div v-if="getClassTestCount(classData.id, 'pending') === 0" class="empty-class-tests">
                      <el-empty description="该班级暂无未截止测试" :image-size="100"></el-empty>
                    </div>
                    <!-- 测试卡片区域 -->
                    <div v-else class="test-cards">
                      <el-card 
                        v-for="test in getClassTests(classData.id, 'pending')" 
                        :key="test.id"
                        shadow="hover"
                        class="test-card completed-test-card"
                        :class="{ 'selected-test': selectedTests.includes(test.id) }">
                        <div class="test-card-header">
                          <h3 class="test-purpose">{{ test.testName || test.examPublish }}</h3>
                          <el-tag type="warning" size="small">未截止</el-tag>
                          <el-tag 
                            v-if="isDeleteMode"
                            :type="selectedTests.includes(test.id) ? 'success' : 'info'"
                            size="mini"
                            @click.native="toggleTestSelection(test.id)"
                            class="selection-tag"
                            style="margin-left: 5px;">
                            {{ selectedTests.includes(test.id) ? '已选择' : '选择' }}
                          </el-tag>
                          <div class="test-meta">
                            <span class="meta-item"><i class="el-icon-time"></i> {{ formatDate(test.endTime) }}</span>
                            <el-button 
                              type="warning" 
                              size="mini" 
                              icon="el-icon-time" 
                              @click.stop="extendDeadline(test.id)"
                              style="margin-left: 5px;">
                              延长截止时间
                            </el-button>
                          </div>
                        </div>
                        <el-tag type="warning" size="mini" v-if="isNearDeadline(test.endTime)" class="deadline-tag">即将截止</el-tag>
                        <!-- 学生信息卡片式展示，与已截止测试一致 -->
                        <div class="student-section" v-if="getTestStudents(test.id).length !== 0">
                          <div class="student-tabs-wrapper">
                            <div class="submission-tabs">
                              <div 
                                class="tab-button" 
                                :class="{active: getTestSubmittedTabState(test.id) === 'submitted'}"
                                @click="setTestSubmittedTabState(test.id, 'submitted')"
                              >
                                已提交 <span class="student-count">({{ getSubmittedStatusStudents(test.id).length }} 人)</span>
                              </div>
                              <div 
                                class="tab-button" 
                                :class="{active: getTestSubmittedTabState(test.id) === 'not-submitted'}"
                                @click="setTestSubmittedTabState(test.id, 'not-submitted')"
                              >
                                未提交 <span class="student-count">({{ getNotSubmittedStatusStudents(test.id).length }} 人)</span>
                              </div>
                            </div>
                          </div>
                          <div v-if="getTestSubmittedTabState(test.id) === 'submitted'" class="student-tab-content">
                            <div v-if="getSubmittedStatusStudents(test.id).length === 0" class="empty-subsection-students">
                              <el-empty description="暂无已提交学生" :image-size="80"></el-empty>
                            </div>
                            <div v-else class="student-grid">
                              <el-card 
                                v-for="student in getSubmittedStatusStudents(test.id)" 
                                :key="student.id + '-submitted'"
                                shadow="hover"
                                class="student-card">
                                <div class="student-card-header">
                                  <div class="student-info">
                                    <span class="student-name">{{ student.name }}</span>
                                    <span class="student-id">(学号: {{ student.id }})</span>
                                  </div>
                                  <el-tag :type="student.completed ? 'success' : 'warning'" size="mini">{{ student.completed ? '已完成' : '已提交' }}</el-tag>
                                </div>
                                <div class="student-card-content">
                                  <div class="progress-info">
                                    <span>完成进度:</span>
                                    <el-progress :percentage="student.totalQuestions > 0 ? Math.floor((student.answeredCount / student.totalQuestions) * 100) : 0" :stroke-width="10" :status="student.completed ? 'success' : ''"></el-progress>
                                  </div>
                                  <div class="score-info" v-if="student.completed">
                                    <span>得分:</span>
                                    <div class="score"><span class="current-score">{{ student.score || 0 }}</span><span class="max-score">/{{ student.maxScore }}</span></div>
                                  </div>
                                  <div class="student-card-actions">
                                    <el-button type="primary" size="small" @click="viewStudentTestDetail(test.id, student.id)"><i class="el-icon-view"></i> 查看答卷</el-button>
                                  </div>
                                </div>
                              </el-card>
                            </div>
                          </div>
                          <div v-if="getTestSubmittedTabState(test.id) === 'not-submitted'" class="student-tab-content">
                            <div v-if="getNotSubmittedStatusStudents(test.id).length === 0" class="empty-subsection-students">
                              <el-empty description="所有学生均已提交" :image-size="80"></el-empty>
                            </div>
                            <div v-else class="student-grid">
                              <el-card 
                                v-for="student in getNotSubmittedStatusStudents(test.id)" 
                                :key="student.id + '-not-submitted'"
                                shadow="hover"
                                class="student-card">
                                <div class="student-card-header">
                                  <div class="student-info">
                                    <span class="student-name">{{ student.name }}</span>
                                    <span class="student-id">(学号: {{ student.id }})</span>
                                  </div>
                                  <el-tag type="info" size="mini">未提交</el-tag>
                                </div>
                                <div class="student-card-content">
                                  <div class="progress-info">
                                    <span>完成进度:</span>
                                    <el-progress :percentage="0" :stroke-width="10"></el-progress>
                                  </div>
                                  <div class="student-card-actions">
                                    <el-button type="primary" size="small" @click="viewStudentTestDetail(test.id, student.id)"><i class="el-icon-view"></i> 查看答卷</el-button>
                                  </div>
                                </div>
                              </el-card>
                            </div>
                          </div>
                        </div>
                        <div v-if="getTestStudents(test.id).length === 0" class="empty-test-students">
                          <el-empty description="该测试暂无学生" :image-size="100"></el-empty>
                        </div>
                      </el-card>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </div>
          </el-tab-pane>
          <!-- 已截止测试标签页 -->
          <el-tab-pane label="已截止测试" name="completed">
            <div class="test-list" >
              <!-- 空状态 -->
              <div v-if="completedTests.length === 0" class="empty-state">
                <div class="empty-container">
                  <el-empty description="暂无已截止的测试">
                    <el-button type="primary" @click="goToTestPublish()">去发布试题</el-button>
                  </el-empty>
                </div>
              </div>
              <!-- 有内容状态 -->
              <div v-if="completedTests.length !== 0" class="hierarchical-selection">
                <!-- 班级层 -->
                <el-collapse accordion>
                  <el-collapse-item v-for="classData in classmap.values()" :key="'completed-'+classData.id">
                    <template slot="title">
                      <div class="class-header">
                        <span class="class-name">{{ classData.name }}</span>
                        <span class="class-count">{{ getClassTestCount(classData.id, 'completed') }} 个测试</span>
                      </div>
                    </template>
                    <!-- 该班级没有已截止测试时显示 -->
                    <div v-if="getClassTestCount(classData.id, 'completed') === 0" class="empty-class-tests">
                      <el-empty description="该班级暂无已截止测试" :image-size="100"></el-empty>
                    </div>
                    <!-- 测试卡片区域 -->
                    <div v-else class="test-cards">
                      <el-card 
                        v-for="test in getClassTests(classData.id, 'completed')" 
                        :key="test.id"
                        shadow="hover"
                        class="test-card completed-test-card"
                        :class="{ 'selected-test': selectedTests.includes(test.id) }">
                        <div class="test-card-header">
                          <h3 class="test-purpose">{{ test.testName || test.examPublish }}</h3>
                          <el-tag type="info" size="small">已截止</el-tag>
                          <el-tag 
                            v-if="isDeleteMode"
                            :type="selectedTests.includes(test.id) ? 'success' : 'info'"
                            size="mini"
                            @click.native="toggleTestSelection(test.id)"
                            class="selection-tag"
                            style="margin-left: 5px;">
                            {{ selectedTests.includes(test.id) ? '已选择' : '选择' }}
                          </el-tag>
                          <div class="test-meta">
                            <span class="meta-item"><i class="el-icon-time"></i> {{ formatDate(test.endTime) }}</span>

                            <el-button 
                              type="warning" 
                              size="mini" 
                              icon="el-icon-time" 
                              @click.stop="extendDeadline(test.id)"
                              style="margin-left: 5px;">
                              延长截止时间
                            </el-button>
                          </div>
                        </div>
                        <!-- 学生信息卡片式展示 -->
                        <div class="student-section" v-if="getTestStudents(test.id).length !== 0">
                          <div class="student-tabs-wrapper">
                            <div class="submission-tabs">
                              <div 
                                class="tab-button" 
                                :class="{active: getTestSubmittedTabState(test.id) === 'submitted'}"
                                @click="setTestSubmittedTabState(test.id, 'submitted')"
                              >
                                已提交 <span class="student-count">({{ getSubmittedStatusStudents(test.id).length }} 人)</span>
                              </div>
                              <div 
                                class="tab-button" 
                                :class="{active: getTestSubmittedTabState(test.id) === 'not-submitted'}"
                                @click="setTestSubmittedTabState(test.id, 'not-submitted')"
                              >
                                未提交 <span class="student-count">({{ getNotSubmittedStatusStudents(test.id).length }} 人)</span>
                              </div>
                            </div>
                          </div>
                          <div v-if="getTestSubmittedTabState(test.id) === 'submitted'" class="student-tab-content">
                            <div v-if="getSubmittedStatusStudents(test.id).length === 0" class="empty-subsection-students">
                              <el-empty description="暂无已提交学生" :image-size="80"></el-empty>
                            </div>
                            <div v-else class="student-grid">
                              <el-card 
                                v-for="student in getSubmittedStatusStudents(test.id)" 
                                :key="student.id + '-submitted'"
                                shadow="hover"
                                class="student-card">
                                <div class="student-card-header">
                                  <div class="student-info">
                                    <span class="student-name">{{ student.name }}</span>
                                    <span class="student-id">(学号: {{ student.id }})</span>
                                  </div>
                                  <el-tag :type="student.completed ? 'success' : 'warning'" size="mini">{{ student.completed ? '已完成' : '已提交' }}</el-tag>
                                </div>
                                <div class="student-card-content">
                                  <div class="progress-info">
                                    <span>完成进度:</span>
                                    <el-progress :percentage="student.totalQuestions > 0 ? Math.floor((student.answeredCount / student.totalQuestions) * 100) : 0" :stroke-width="10" :status="student.completed ? 'success' : ''"></el-progress>
                                  </div>
                                  <div class="score-info" v-if="student.completed">
                                    <span>得分:</span>
                                    <div class="score"><span class="current-score">{{ student.score || 0 }}</span><span class="max-score">/{{ student.maxScore }}</span></div>
                                  </div>
                                  <div class="student-card-actions">
                                    <el-button type="primary" size="small" @click="viewStudentTestDetail(test.id, student.id)"><i class="el-icon-view"></i> 查看答卷</el-button>
                                  </div>
                                </div>
                              </el-card>
                            </div>
                          </div>
                          <div v-if="getTestSubmittedTabState(test.id) === 'not-submitted'" class="student-tab-content">
                            <div v-if="getNotSubmittedStatusStudents(test.id).length === 0" class="empty-subsection-students">
                              <el-empty description="所有学生均已提交" :image-size="80"></el-empty>
                            </div>
                            <div v-else class="student-grid">
                              <el-card 
                                v-for="student in getNotSubmittedStatusStudents(test.id)" 
                                :key="student.id + '-not-submitted'"
                                shadow="hover"
                                class="student-card">
                                <div class="student-card-header">
                                  <div class="student-info">
                                    <span class="student-name">{{ student.name }}</span>
                                    <span class="student-id">(学号: {{ student.id }})</span>
                                  </div>
                                  <el-tag type="info" size="mini">未提交</el-tag>
                                </div>
                                <div class="student-card-content">
                                  <div class="progress-info">
                                    <span>完成进度:</span>
                                    <el-progress :percentage="0" :stroke-width="10"></el-progress>
                                  </div>
                                  <div class="student-card-actions">
                                    <el-button type="primary" size="small" @click="viewStudentTestDetail(test.id, student.id)"><i class="el-icon-view"></i> 查看答卷</el-button>
                                  </div>
                                </div>
                              </el-card>
                            </div>
                          </div>
                        </div>
                        <div v-if="getTestStudents(test.id).length === 0" class="empty-test-students">
                          <el-empty description="该测试暂无学生" :image-size="100"></el-empty>
                        </div>
                      </el-card>
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
    <!-- 路由视图，用于显示子路由内容 -->
    <router-view v-if="$route.path.includes('/new')" />
  </div>
</template>
<script>
import axios from 'axios';  

export default {
  name: 'MyPublish',
  data() {
    return {
      userId: '',
      loading: false,
      refreshing: false,
      testlist: [],
      pendingTests: [],
      completedTests: [],
      pendingMap: new Map(),
      completedMap: new Map(),
      classmap: new Map(),
      activeTab: 'pending',
      componentKey: 0, 
      selectedTests: [],
      testSelectionMap: {},
      tabActiveStates: {},
      testSubmittedTabStates: {}, // 用于跟踪每个测试的提交状态标签页状态
      isDeleteMode: false // 是否处于删除选择模式
    }
  },
  created() {
    // 确保getUserId完成后再获取测试数据
    const userIdSuccess = this.getUserId();
    if (userIdSuccess) {
      this.fetchMyTests();
      this.checkTestSubmission();
    } else {
      console.error('无法获取用户ID，跳过数据加载');
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      console.log('MyPublish beforeRouteEnter 触发，来源页面:', from.name);
      
      // 检查是否从PublishDetail返回
      if (from.name === 'PublishDetail') {
        console.log('从PublishDetail返回，检查原始teacherId');
        
        // 获取原始教师ID
        const originalTeacherId = sessionStorage.getItem('original_teacher_id');
        if (originalTeacherId) {
          console.log('恢复原始teacherId:', originalTeacherId);
          vm.userId = originalTeacherId;
          sessionStorage.setItem('teacherId', originalTeacherId);
        }
      }
      
      // 确保有用户ID - 将这步骤放在最前面确保先有用户ID
      if (!vm.userId) {
        vm.getUserId();
        console.log('获取到的userId:', vm.userId);
      }
      
      if (!vm.userId) {
        console.error('用户ID为空或无效，这可能导致API返回空数据');
        vm.$message.error('无法获取用户信息，请重新登录');
        return;
      }
      
      // 检查是否需要刷新数据
      if (from.name === 'PublishDetail' || sessionStorage.getItem('need_refresh_publish') === 'true') {
        console.log('检测到从PublishDetail返回或需要刷新标记，执行强制刷新');
        // 清除标记
        sessionStorage.removeItem('need_refresh_publish');
        // 强制刷新和重渲染
        vm.$nextTick(() => {
          vm.refreshWithFullReset();
        });
      } else {
        // 正常刷新数据
        vm.fetchMyTests();
      }
      
      // 检查是否刚从TestDetail提交了测试
      vm.checkTestSubmission();
    });
  },
  activated() {
    console.log('MyPublish activated 生命周期钩子触发');
    
    if (sessionStorage.getItem('need_refresh_publish') === 'true') {
      console.log('检测到需要刷新标记，执行强制刷新');
      sessionStorage.removeItem('need_refresh_publish');
      this.$nextTick(() => {
        this.refreshWithFullReset();
      });
    } else {
      this.fetchMyTests();
    }
    
    this.checkTestSubmission();
  },
  methods: {
    // 跳转到测试发布页面
    goToTestPublish() {
      try {
        // 获取当前用户ID
        const userId = this.getUserIdForNavigation();
        // 使用新的独立路由路径
        const path = `/manage/${userId}/teach/testPublish`;
        console.log('跳转到路径:', path);
        
        // 使用路径跳转
        this.$router.push(path);
      } catch (error) {
        console.error('导航错误:', error);
        this.$message.error('跳转失败，请刷新页面后重试');
      }
    },

    // 获取用于导航的用户ID
    getUserIdForNavigation() {
      // 先从当前组件的id获取
      if (this.id) {
        return this.id;
      }
      // 如果当前组件没有，尝试从路由参数获取
      if (this.$route && this.$route.params && this.$route.params.id) {
        return this.$route.params.id;
      }
      // 如果路由参数也没有，尝试从SessionStorage获取
      const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '{}');
      if (userInfo && userInfo.userId) {
        return userInfo.userId;
      }
      // 都没有则返回空值
      return '';
    },
    getUserId() {
      try {
        if (this.$store && this.$store.state && this.$store.state.userInfo && this.$store.state.userInfo.userId) {
          this.userId = this.$store.state.userInfo.userId;
          console.log('从Vuex获取到userId:', this.userId);
        } 
        else if (localStorage.getItem('userInfo')) {
          const userInfo = JSON.parse(localStorage.getItem('userInfo'));
          if (userInfo && userInfo.userId) {
            this.userId = userInfo.userId;
            console.log('从localStorage获取到userId:', this.userId);
          }
        }
        
        if (!this.userId && this.$route.params.id) {
          this.userId = this.$route.params.id;
          console.log('从URL参数获取到userId:', this.userId);
        }
        
        if (this.userId) {
          if (typeof this.userId === 'string' && !this.userId.match(/^\d+$/)) {
            console.warn('userId包含非数字字符，这可能导致API调用失败:', this.userId);
            const numericPart = this.userId.match(/\d+/);
            if (numericPart) {
              this.userId = numericPart[0];
              console.log('提取的数字部分userId:', this.userId);
            }
          }
          sessionStorage.setItem('teacherId', this.userId);
        }
        
        if (!this.userId) {
          console.error('无法获取用户ID, 数据加载可能会失败');
          return false;
        } else {
          console.log('成功获取用户ID:', this.userId);
          return true;
        }
      } catch (error) {
        console.error('获取用户ID时出错:', error);
        return false;
      }
    },
    async fetchMyTests() {
      console.log('开始获取测试数据');
      this.loading = true;
      
      // 清空现有数据
      this.testlist = [];
      this.pendingTests = [];
      this.completedTests = [];
      this.pendingMap.clear();
      this.completedMap.clear();
      this.classmap.clear();
      this.selectedTests = [];
      this.testSelectionMap = {};
      
      try {
        // 再次确保教师ID有效
        let teacherId = this.userId;
        
        // 如果没有教师ID，尝试重新获取
        if (!teacherId) {
          console.log('教师ID为空，尝试重新获取');
          const success = this.getUserId();
          if (success) {
            teacherId = this.userId;
          }
        }
        
        if (!teacherId) {
          console.error('无法获取有效的教师ID，停止数据获取');
          this.$message.error('无法获取教师信息，请重新登录');
          this.loading = false;
          return;
        }
        
        console.log('发送请求获取测试数据, 教师ID:', teacherId);
        
        // 使用新的基于result_name表的API
        const response = await axios.get('/question/publish/teacher', { 
          params: { teacherId, _t: new Date().getTime() } 
        });
        console.log('获取到的测试数据:', response.data);
        
        if (!response.data || response.data.code !== 200) {
          console.log('获取测试数据失败:', response.data?.msg || '未知错误');
          this.loading = false;
          return;
        }
        
        const data = response.data.data;
        if (!data || data.length === 0) {
          console.log('没有获取到测试数据');
          this.loading = false;
          return;
        }
    
        // 处理新的数据结构
        data.forEach(classData => {
          console.log('处理班级数据:', classData);
          if (!classData || !classData.classId) return;
          
          // 保存班级信息
          this.classmap.set(classData.classId, {
            id: classData.classId,
            name: classData.className
          });
          
          // 处理该班级的测试数据
          if (classData.tests && classData.tests.length > 0) {
            console.log(`班级${classData.className}有${classData.tests.length}个测试`);
            classData.tests.forEach(test => {
              console.log('处理测试:', test);
              if (!test || !test.testName) return;
              
              // 为每个测试生成唯一ID（使用班级ID + 测试名称）
              const testId = test.testName;
              
              // 构建测试对象
              const testObj = {
                id: testId,
                examPublish: test.testName,
                testName: test.testName,
                classId: classData.classId,
                className: classData.className,
                resultIds: test.resultIds,
                startTime: test.startTime,
                endTime: test.endTime,
                answerTime: test.answerTime,
                purpose: test.purpose,
                totalStudents: test.totalStudents,
                submittedCount: test.submittedCount,
                completedCount: test.completedCount,
                averageScore: test.averageScore,
                submissionRate: test.submissionRate,
                completionRate: test.completionRate,
                studentDetails: test.studentDetails || [],
                status: test.status,
                isExpired: test.isExpired,
                
                // 为了兼容现有的UI逻辑，构建results数组
                results: test.studentDetails ? test.studentDetails.map(detail => ({
                  id: detail.id,
                  studentId: detail.student_id,
                  studentName: detail.studentName,
                  questionId: detail.question_id,
                  score: detail.score,
                  maxScore: detail.max_score,
                  startTime: detail.start_time,
                  endTime: detail.end_time,
                  answerTime: detail.answer_time,
                  purpose: detail.purpose,
                  isSubmit: detail.is_submit,
                  isCorrect: detail.is_correct,
                  comment: detail.comment,
                  examPublish: test.testName
                })) : []
              };
              
              // 添加到总列表
              this.testlist.push(testObj);
              
              // 根据状态分类
              console.log(`测试${test.testName}状态: status=${test.status}, isExpired=${test.isExpired}`);
              if (test.status === 'completed' || test.isExpired) {
                console.log(`测试${test.testName}归类为已截止`);
                this.completedTests.push(testObj);
                this.completedMap.set(testId, testObj);
              } else {
                console.log(`测试${test.testName}归类为未截止`);
                this.pendingTests.push(testObj);
                this.pendingMap.set(testId, testObj);
              }
            });
          }
        });
        
        console.log('处理后的测试数据:');
        console.log('- 总测试数:', this.testlist.length);
        console.log('- 未截止测试数:', this.pendingTests.length);
        console.log('- 已截止测试数:', this.completedTests.length);
        console.log('- 班级数:', this.classmap.size);
        
      } catch (error) {
        console.error('获取测试数据出错:', error);
        this.$message.error('获取测试数据失败: ' + (error.response?.data?.msg || error.message));
      } finally {
        this.loading = false;
      }
    },
    calculateProgress(answers, questionCount) {
      if (!answers) return 0;
      
      const completedQuestions = Object.values(answers).filter(answer => answer && answer.trim() !== '').length;
      return Math.round((completedQuestions / questionCount) * 100);
    },
    formatDate(dateString) {
      if (!dateString) return '未设置';
      
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    
    // 查看测试详情
    viewTestDetail(testId) {
      this.$router.push(`/manage/teach/test-detail?testId=${testId}`);
    },
    
    // 查看完成详情
    viewCompletionDetails(testId) {
      // 实际跳转到学生列表页面
      this.$router.push(`/manage/teach/test-stats?testId=${testId}`);
    },
    
    // 延长单个测试截止时间
    extendDeadline(testId) {
      this.selectedTests = [testId];
      this.extendSelectedDeadlines();
    },
    
    // 延长选中测试的截止时间
    extendSelectedDeadlines() {
      if (this.selectedTests.length === 0) {
        this.$message.warning('请先选择要延长时间的测试');
        return;
      }
      
      this.$prompt('请输入要延长的分钟数', '延长截止时间', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[1-9]\d*$/,
        inputErrorMessage: '请输入正整数'
      }).then(({ value }) => {
        const minutes = parseInt(value);
        
        // 获取教师ID
        const teacherId = this.userId;
        if (!teacherId) {
          this.$message.error('无法获取教师ID');
          return;
        }
        
        // 为每个选中的测试延长截止时间
        const promises = this.selectedTests.map(testId => {
          // 根据testId找到对应的测试对象
          const test = this.testlist.find(t => t.id === testId);
          if (!test) {
            console.error('未找到测试对象:', testId);
            return Promise.reject(new Error('未找到测试对象'));
          }
          
          return axios.post('/question/extendExamTime', {
            testName: test.testName, // 使用测试名称
            teacherId: teacherId,
            minutes: minutes
          });
        });
        
        Promise.all(promises)
          .then(responses => {
            const successCount = responses.filter(response => response.data.code === 200).length;
            const failCount = responses.length - successCount;
            
            if (successCount > 0) {
              this.$message.success(`成功延长 ${successCount} 个测试的截止时间${minutes}分钟`);
              if (failCount > 0) {
                this.$message.warning(`${failCount} 个测试延长失败`);
              }
              // 刷新数据
              this.refreshData();
            } else {
              this.$message.error('延长截止时间失败');
            }
          })
          .catch(error => {
            console.error('延长截止时间出错:', error);
            this.$message.error('延长截止时间失败，请稍后再试');
          });
      }).catch(() => {
        // 用户取消操作
      });
    },
    
    // 进入删除模式
    enterDeleteMode() {
      this.isDeleteMode = true;
      this.selectedTests = []; // 清空之前的选择
      this.$message.info('请选择要删除的测试，然后点击"确认删除"');
    },
    
    // 取消删除模式
    cancelDeleteMode() {
      this.isDeleteMode = false;
      this.selectedTests = []; // 清空选择
      this.$message.info('已取消删除操作');
    },
    
    // 确认删除
    confirmDelete() {
      if (this.selectedTests.length === 0) {
        this.$message.warning('请先选择要删除的测试');
        return;
      }
      
      // 获取选中的测试名称列表
      const selectedTestNames = this.selectedTests.map(testId => {
        const test = this.testlist.find(t => t.id === testId);
        return test ? test.testName : null;
      }).filter(name => name !== null);
      
      if (selectedTestNames.length === 0) {
        this.$message.error('无法获取选中测试的信息');
        return;
      }
      
      this.$confirm(`确定要删除选中的 ${this.selectedTests.length} 个测试吗？\n\n测试名称：${selectedTestNames.join(', ')}\n\n此操作不可恢复，将删除所有相关的答题记录。`, '确认删除', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }).then(() => {
        // 执行删除操作
        this.deleteSelectedTests(selectedTestNames);
      }).catch(() => {
        // 用户取消删除
        this.$message.info('已取消删除操作');
      });
    },
    
    // 删除选中的测试
    async deleteSelectedTests(testNames) {
      const teacherId = this.userId;
      if (!teacherId) {
        this.$message.error('无法获取教师ID');
        return;
      }
      
      try {
        // 为每个选中的测试调用删除接口
        const promises = testNames.map(testName => {
          return this.deleteSingleTest(testName, teacherId);
        });
        
        const results = await Promise.all(promises);
        let successCount = 0;
        let failCount = 0;
        const failedTests = [];
        
        results.forEach((result, index) => {
          if (result.success) {
            successCount++;
          } else {
            failCount++;
            failedTests.push(testNames[index]);
          }
        });
        
        if (successCount > 0) {
          this.$message.success(`成功删除 ${successCount} 个测试${failCount > 0 ? `，${failCount} 个失败` : ''}`);
          if (failCount > 0) {
            console.error('删除失败的测试:', failedTests);
          }
          // 退出删除模式，清空选择并刷新数据
          this.isDeleteMode = false;
          this.selectedTests = [];
          this.testSelectionMap = {};
          this.fetchMyTests();
        } else {
          this.$message.error('删除测试失败');
        }
      } catch (error) {
        console.error('删除测试出错:', error);
        this.$message.error('删除测试时发生错误');
      }
    },
    
    // 删除单个测试
    async deleteSingleTest(testName, teacherId) {
      try {
        const response = await axios.post('/question/deleteTest', {
          testName: testName,
          teacherId: teacherId
        });
        
        if (response.data.code === 200) {
          console.log(`测试 ${testName} 删除成功:`, response.data.data);
          return { success: true, data: response.data.data };
        } else {
          console.error(`测试 ${testName} 删除失败:`, response.data.message);
          return { success: false, message: response.data.message };
        }
      } catch (error) {
        console.error(`测试 ${testName} 删除出错:`, error);
        return { success: false, message: error.message };
      }
    },
    

    
    // 切换测试选择状态
    toggleTestSelection(testId) {
      console.log('切换测试选择状态，testId:', testId, '当前selectedTests:', this.selectedTests);
      const index = this.selectedTests.indexOf(testId);
      if (index > -1) {
        this.selectedTests.splice(index, 1);
        console.log('取消选择测试，剩余selectedTests:', this.selectedTests);
      } else {
        this.selectedTests.push(testId);
        console.log('选择测试，当前selectedTests:', this.selectedTests);
      }
    },
    
    // 获取测试完成率
    getCompletionRate(testId) {
      const test = this.pendingTests.find(t => t.id === testId);
      if (!test) return 0;
      
      const questionCount = test.questionCount;
      const completedQuestions = test.answers ? Object.values(test.answers).filter(answer => answer && answer.trim() !== '').length : 0;
      
      return Math.round((completedQuestions / questionCount) * 100);
    },
    
    // 获取完成学生数
    getCompletedCount(testId) {
      const test = this.completedTests.find(t => t.id === testId);
      if (!test || !test.questions) return 0;
      
      const studentIds = [...new Set(test.questions.filter(q => q.answer !== null).map(q => q.studentId))];
      return studentIds.length;
    },
    
    // 获取未完成学生数
    getUncompletedCount(testId) {
      const test = this.completedTests.find(t => t.id === testId);
      if (!test || !test.questions) return 0;
      
      const studentIds = [...new Set(test.questions.filter(q => q.answer === null).map(q => q.studentId))];
      return studentIds.length;
    },
    
    // 获取平均分
    getAverageScore(testId) {
      const test = this.completedTests.find(t => t.id === testId);
      if (!test || !test.questions) return 0;
      
      const completedStudents = test.questions.filter(q => q.answer !== null);
      
      if (completedStudents.length === 0) return 0;
      
      const totalScore = completedStudents.reduce((sum, student) => {
        return sum + (student.score || 0);
      }, 0);
      
      return (totalScore / completedStudents.length).toFixed(1);
    },
    
    // 返回进度条颜色
    progressColor() {
      return [
        {color: '#f56c6c', percentage: 20},
        {color: '#e6a23c', percentage: 50},
        {color: '#5cb87a', percentage: 80},
        {color: '#1989fa', percentage: 100}
      ];
    },
    
    formatDateTime(dateString) {
      if (!dateString) return '未设置';
      
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    isNearDeadline(deadline) {
      if (!deadline) return false;
      
      const deadlineDate = new Date(deadline);
      const now = new Date();
      const timeDiff = deadlineDate - now;
      
      return timeDiff > 0 && timeDiff < 1 * 60 * 60 * 1000;
    },
    viewTestResult(testId) {
      const testItem = this.testlist.find(t => t.id === testId);
      
      if (testItem) {
        sessionStorage.setItem('current_test_info', JSON.stringify({
          id: testItem.id,
          purpose: testItem.purpose,
          totalScore: testItem.score,
          questionCount: testItem.questionCount || 0,
          endTime: testItem.endTime,
          status: testItem.status
        }));
        
        if (testItem.questions) {
          sessionStorage.setItem('current_test_details', JSON.stringify(testItem.questions));
        }
      } else {
        console.error('未找到对应的测试项目!');
      }
      
      this.$router.push({
        name: 'PublishDetail',
        params: { 
          id: testId,
          studentId: null
        }
      });
    },
    
    refreshData() {
      this.refreshing = true;
      this.fetchMyTests();
    },
    
    refreshTests() {
      this.refreshing = true;
      
      try {
        this.pendingTests = [];
        this.completedTests = [];
        this.testlist = [];
        this.pendingMap.clear();
        this.completedMap.clear();
        this.classmap.clear();
        
        this.fetchMyTests();
        
        this.forceRerender();
        
        this.$message.success('数据已刷新');
      } catch (error) {
        console.error('刷新数据出错:', error);
        this.$message.error('刷新数据失败，请稍后再试');
      } finally {
        this.refreshing = false;
      }
    },
    
    refreshWithFullReset() {
      this.refreshing = true;
      console.log('开始执行完全重置刷新');
      
      try {
        this.pendingTests = [];
        this.completedTests = [];
        this.testlist = [];
        this.pendingMap = new Map();
        this.completedMap = new Map();
        this.classmap = new Map();
        
        this.$nextTick();
        
        this.fetchMyTests();
        
        this.componentKey += 1;
        
        this.$nextTick();
        
        console.log('完全重置刷新完成，组件已重新渲染');
        this.$message.success('数据已刷新');
      } catch (error) {
        console.error('刷新数据出错:', error);
        this.$message.error('刷新数据失败，请稍后再试');
      } finally {
        this.refreshing = false;
      }
    },
    
    forceRerender() {
      this.componentKey += 1;
    },
    checkTestSubmission() {
      const testJustSubmitted = localStorage.getItem('test_just_submitted');
      if (testJustSubmitted === 'true') {
        console.log('检测到刚刚提交了测试，强制刷新数据');
        
        localStorage.removeItem('test_just_submitted');
        
        this.refreshTests();
        
        this.$message.success('测试已提交，数据已更新');
      }
    },
    getClassTestCount(classId, status) {
      const tests = status === 'pending' ? this.pendingTests : this.completedTests;
      
      const filteredTests = tests.filter(test => 
        test.classId && 
        test.classId === classId
      );
      
      // 根据测试ID(publishId)去重
      const uniqueTestIds = [...new Set(filteredTests.map(test => test.id))];
      
      // 返回去重后的数量
      return uniqueTestIds.length;
    },
    
    getClassTests(classId, status) {
      const tests = status === 'pending' ? this.pendingTests : this.completedTests;
      
      // 先按班级筛选测试
      const filteredTests = tests.filter(test => 
        test.classId && 
        test.classId === classId
      );
      
      // 创建Map以便按ID去重，保留最新的测试信息
      const uniqueTestsMap = new Map();
      filteredTests.forEach(test => {
        uniqueTestsMap.set(test.id, test);
      });
      
      // 转换回数组
      const uniqueTests = Array.from(uniqueTestsMap.values());
      
      console.log(`获取班级 ${classId} 的${status}测试列表(去重后)`, 
        uniqueTests.map(t => ({id: t.id, purpose: t.purpose}))
      );
      
      return uniqueTests;
    },
    getClassCompletionRate(classId, testId) {
      const test = this.pendingTests.find(t => t.id === testId);
      if (!test) return 0;
      
      const questionCount = test.questionCount;
      const completedQuestions = test.answers ? Object.values(test.answers).filter(answer => answer && answer.trim() !== '').length : 0;
      
      return Math.round((completedQuestions / questionCount) * 100);
    },
    viewTestStats(testId, classId) {
      this.$router.push({
        name: 'TestStats',
        params: { testId, classId }
      });
    },
    getCompletedStudentsCount(testId) {
      const test = this.completedTests.find(t => t.id === testId);
      if (!test || !test.questions) return 0;
      
      const studentIds = [...new Set(test.questions.filter(q => q.answer !== null).map(q => q.studentId))];
      return studentIds.length;
    },
    exportTestResults(testId, classId) {
      this.$message.info('成绩导出功能开发中');
      
      const test = this.completedTests.find(t => t.id === testId);
      if (test) {
        const classStudentResults = test.questions.filter(q => {
          return q.classId === classId || true; 
        });
        
        console.log('准备导出的数据:', classStudentResults);
      }
    },
    getCompletedTestStudents(testId) {
      const allStudents = this.getTestStudents(testId);
      return allStudents.filter(student => student.completed);
    },
    getUncompletedTestStudents(testId) {
      const allStudents = this.getTestStudents(testId);
      return allStudents.filter(student => !student.completed);
    },
    getSubmittedStatusStudents(testId) {
      const test = this.testlist.find(t => t.id === testId);
      if (!test || !test.results) return [];
      
      // 根据is_submit字段判断已提交状态
      const submittedStudents = test.results.filter(result => 
        result.isSubmit === '1' || result.isSubmit === 1
      );
      
      // 按学生ID去重并构建完整的学生信息
      const uniqueStudents = new Map();
      submittedStudents.forEach(result => {
        if (!uniqueStudents.has(result.studentId)) {
          uniqueStudents.set(result.studentId, {
            id: result.studentId,
            name: result.studentName,
            isSubmit: result.isSubmit,
            score: result.score || 0,
            maxScore: result.maxScore || 0,
            completed: result.isSubmit === '1' || result.isSubmit === 1,
            totalQuestions: 1, // 假设每个结果对应一题，实际可能需要调整
            answeredCount: result.isSubmit === '1' || result.isSubmit === 1 ? 1 : 0
          });
        }
      });
      
      return Array.from(uniqueStudents.values());
    },
    
    // 获取未提交状态的学生
    getNotSubmittedStatusStudents(testId) {
      const test = this.testlist.find(t => t.id === testId);
      if (!test || !test.results) return [];
      
      // 根据is_submit字段判断未提交状态
      const notSubmittedStudents = test.results.filter(result => 
        result.isSubmit === '0' || result.isSubmit === 0 || !result.isSubmit
      );
      
      // 按学生ID去重并构建完整的学生信息
      const uniqueStudents = new Map();
      notSubmittedStudents.forEach(result => {
        if (!uniqueStudents.has(result.studentId)) {
          uniqueStudents.set(result.studentId, {
            id: result.studentId,
            name: result.studentName,
            isSubmit: result.isSubmit,
            score: 0,
            maxScore: result.maxScore || 0,
            completed: false,
            totalQuestions: 1,
            answeredCount: 0
          });
        }
      });
      
      return Array.from(uniqueStudents.values());
    },
    
    getTestStudents(testId) {
      const test = this.testlist.find(t => t.id === testId);
      console.log(`获取测试${testId}的学生数据:`, test ? (test.results || []) : []);
      if (!test || !test.results) return [];
      
      // 去重学生ID
      const uniqueStudents = new Map();
      test.results.forEach(result => {
        if (result.studentId && !uniqueStudents.has(result.studentId)) {
          uniqueStudents.set(result.studentId, {
            id: result.studentId,
            name: result.studentName || `学生${result.studentId}`,
            completed: result.isSubmit === '1' || result.isSubmit === 1,
            isSubmit: result.isSubmit,
            score: result.score || 0,
            maxScore: result.maxScore || 0,
            submissionStatus: result.isSubmit === '1' || result.isSubmit === 1 ? '已提交' : '未提交'
          });
        }
      });
      
      const students = Array.from(uniqueStudents.values());
      console.log(`测试${testId}的学生列表:`, students);
      return students;
    },
    
    // 获取测试的提交状态标签页状态
    getTestSubmittedTabState(testId) {
      return this.testSubmittedTabStates[testId] || 'not-submitted';
    },
    
    // 设置测试的提交状态标签页状态
    setTestSubmittedTabState(testId, state) {
      this.$set(this.testSubmittedTabStates, testId, state);
    },
    
    // 查看学生试卷详情
    viewStudentTestDetail(testId, studentId) {
      console.log('查看学生试卷详情 - testId:', testId, 'studentId:', studentId);
      const testItem = this.testlist.find(t => t.id === testId);
      console.log('找到的测试项目:', testItem);
      if (testItem) {
        const testInfo = {
          id: testItem.id,
          testName: testItem.testName,
          purpose: testItem.purpose,
          endTime: testItem.endTime,
          status: testItem.status,
          studentId: studentId,
          classId: testItem.classId,
          className: testItem.className
        };
        sessionStorage.setItem('current_test_info', JSON.stringify(testInfo));
        // 只保存当前学生的答卷详情
        const studentResult = (testItem.results || []).filter(r => r.studentId == studentId);
  
        // 单独保存studentId以便页面刷新时使用
        sessionStorage.setItem('current_student_id', studentId.toString());
        sessionStorage.setItem('current_test_id', testId.toString());
        // 跳转到详情页面，通过查询参数传递studentId
        this.$router.push({
          name: 'PublishDetail',
          params: { id: testId ,
            studentResult: studentResult
          },
          query: { studentId }
        });
      } else {
        this.$message.error('未找到测试数据，请刷新页面后重试');
      }
    }
  }
}
</script>
<style scoped>
.publish-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
  width: 100%;
}

.publish-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding-bottom: 6px;
  border-bottom: 1px solid #ebeef5;
}

.header-actions {
  display: flex;
  gap: 6px;
  align-items: center;
  flex-wrap: wrap;
}

.selected-count {
  margin-right: 6px;
  color: #409EFF;
  font-weight: 500;
  background-color: rgba(64, 158, 255, 0.08);
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 13px;
}

.section-title {
  display: flex;
  align-items: center;
  font-weight: 600;
  margin-bottom: 8px;
  font-size: 13px;
  color: #303133;
}

.section-title i {
  margin-right: 3px;
}

.empty-state {
  padding: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.empty-container {
  width: 100%;
  max-width: 320px;
  text-align: center;
}

.test-cards {
  display: grid;
  grid-template-columns: 1fr;
  gap: 8px;
  margin-top: 8px;
}

.test-card {
  transition: all 0.2s ease;
  margin-bottom: 0;
  border-radius: 5px;
  overflow: hidden;
  border: 1px solid #ebeef5;
  position: relative;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);
  padding: 10px 12px;
}

.test-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);
}

.test-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, #409EFF, #67C23A);
  opacity: 0;
  transition: opacity 0.2s ease;
}

.test-card:hover::before {
  opacity: 1;
}

.selected-test {
  border-color: #409EFF;
  box-shadow: 0 0 6px rgba(64, 158, 255, 0.13);
}

.class-header {
  display: flex;
  align-items: center;
  font-size: 13px;
  gap: 6px;
}

.class-name {
  font-weight: 600;
  margin-right: 6px;
}

.class-count {
  color: #909399;
  font-size: 12px;
}

.test-title {
  font-size: 13px;
  font-weight: 600;
  margin-bottom: 6px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.test-status {
  margin-left: 6px;
  font-size: 12px;
}

.test-status.pending {
  color: #E6A23C;
}

.test-status.completed {
  color: #67C23A;
}

.test-deadline {
  color: #F56C6C;
  font-size: 12px;
  margin-top: 2px;
}

.test-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
  margin-top: 4px;
  margin-bottom: 6px;
  color: #606266;
  font-size: 12px;
}

.test-details-collapse {
  margin-top: 6px;
}

.student-section {
  margin-bottom: 8px;
}

.student-cards, .student-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 6px;
  margin-top: 6px;
}

.student-card {
  display: flex;
  flex-direction: column;
  padding: 8px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  transition: all 0.2s;
  background: #fff;
}

.student-card:hover {
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
}

.student-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.student-name {
  font-weight: 500;
  font-size: 13px;
}

.student-status {
  font-size: 11px;
  padding: 1px 4px;
  border-radius: 6px;
}

.status-completed {
  background-color: #F0F9EB;
  color: #67C23A;
}

.status-pending {
  background-color: #FDF6EC;
  color: #E6A23C;
}

.student-progress {
  margin: 4px 0;
}

.student-score {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 4px;
  font-size: 12px;
}

.test-stats-section {
  margin-top: 8px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 6px;
  margin-top: 6px;
}

.stat-card {
  padding: 8px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  background: #fff;
}

.stat-value {
  font-size: 15px;
  font-weight: 600;
  margin: 4px 0;
  color: #409EFF;
}

.stat-label {
  color: #606266;
  font-size: 12px;
}

.test-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
  gap: 6px;
}

.empty-test-students {
  padding: 8px;
  text-align: center;
}

.hierarchical-selection {
  margin-top: 6px;
}

.empty-class-tests {
  padding: 8px;
  text-align: center;
  font-weight: 600;
  margin-right: 6px;
}

.student-id {
  color: #909399;
  font-size: 0.8em;
}

.student-meta {
  margin-left: auto;
  display: flex;
  gap: 6px;
}

.student-detail-actions {
  padding: 4px 8px;
  display: flex;
  justify-content: flex-end;
  background-color: #f9f9f9;
  border-radius: 4px;
  margin-top: 4px;
}

.empty-test-students {
  padding: 8px;
  text-align: center;
}

.test-header, .test-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 8px;
  margin-bottom: 0;
  background-color: #fafafa;
  border-bottom: 1px solid #f0f2f5;
}

.test-purpose {
  margin: 0;
  font-size: 13px;
  font-weight: 600;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 70%;
  position: relative;
  padding-left: 4px;
}

.test-purpose::before {
  content: '';
  position: absolute;
  left: 0;
  top: 2px;
  bottom: 2px;
  width: 2px;
  background-color: #409EFF;
  border-radius: 2px;
}

.test-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 6px;
  color: #606266;
  font-size: 12px;
}

.test-card-meta {
  padding: 8px;
  margin-bottom: 0;
}

.meta-item {
  font-size: 12px;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  color: #606266;
  padding: 4px 6px;
  background-color: #f9fafc;
  border-radius: 3px;
  transition: all 0.2s ease;
}

.meta-item:hover {
  background-color: #f0f2f5;
}

.meta-item:last-child {
  margin-bottom: 0;
}

.meta-item i {
  margin-right: 6px;
  color: #409EFF;
  font-size: 13px;
}

/* 学生提交状态选项卡样式 */
.student-tabs-wrapper {
  margin-bottom: 10px;
}

.submission-tabs {
  display: flex;
  border-bottom: 1px solid #e0e0e0;
  margin-bottom: 8px;
}

.tab-button {
  padding: 4px 10px;
  cursor: pointer;
  font-size: 12px;
  text-align: center;
  flex: 1;
  transition: all 0.3s;
  border-bottom: 2px solid transparent;
  color: #606266;
}

.tab-button.active {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
  font-weight: 500;
}

.tab-button .student-count {
  display: inline-block;
  font-size: 11px;
  margin-left: 2px;
  transition: all 0.3s ease;
  color: #606266;
}

.tab-button.active .student-count {
  color: #409EFF;
}

.tab-button:hover .student-count {
  transform: scale(1.04);
}

.student-tab-content {
  padding-top: 2px;
}

.el-input-number, .el-input__inner, .el-textarea__inner {
  font-size: 13px !important;
  height: 24px !important;
  min-height: 24px !important;
}

.el-button {
  font-size: 13px !important;
  padding: 3px 8px !important;
  height: 24px !important;
}

.el-tag {
  font-size: 11px !important;
  height: 18px !important;
  line-height: 18px !important;
  padding: 0 5px !important;
}

</style>